<!-- 生产入库-编辑 -->
<template>
	<view class="content">
		<!-- 顶部导航栏 -->
		<u-navbar :fixed="false" :title="titleName" :autoBack="true" :safeAreaInsetTop="true" leftIconColor="#fff">
			<view slot="right" @click="openScan">
				<uni-icons v-if="!$utils.isPda()" type="scan" size="24" color="#fff"></uni-icons>
			</view>
		</u-navbar>

		<!-- 表头信息 -->
		<view class="headTabWrap">
			<uni-segmented-control :current="currenTabIndex" :values="items" style-type="text" active-color="#51d0d0"
				@clickItem="onClickItem" />
			<view class="panelBtn" @click="togglePanel()">
				<uni-icons v-if="currenTabIndex==null" type="eye" size="24" color="#51D0D0"></uni-icons>
				<uni-icons v-else type="eye-slash" size="24" color="#8A8A8A"></uni-icons>
			</view>
		</view>

		<view class="headTabContent">
			<view v-show="currenTabIndex === 0">
				<u--form labelPosition="left" :model="formData" labelWidth="80">
					<u-form-item prop="FCode" borderBottom>
						<view class="item-label">
							<uni-icons fontFamily="CustomFontPlatform"
								color="#808080">{{$utils.toUniCode('&#xed1c;')}}</uni-icons>
							<text class="label-text">单据编号</text>
						</view>
						<u--input :value="formData.FCode" disabled disabledColor="#fff" placeholder="自动生成"
							border="none"></u--input>
					</u-form-item>
					<u-form-item prop="FDate" borderBottom>
						<view class="item-label">
							<uni-icons fontFamily="CustomFontPlatform"
								color="#808080">{{$utils.toUniCode('&#xe7ac;')}}</uni-icons>
							<text class="label-text">单据日期</text>
						</view>
						<u--input :value="formData.FDate" disabled disabledColor="#fff" placeholder="单据日期"
							border="none"></u--input>
					</u-form-item>
					<u-form-item prop="BillNO" borderBottom>
						<view class="item-label">
							<uni-icons fontFamily="CustomFontPlatform"
								color="#808080">{{$utils.toUniCode('&#xed21;')}}</uni-icons>
							<text class="label-text">工单编号</text>
							<text class="required">*</text>
						</view>
						<u--input :value="formData.BillNO" disabled disabledColor="#fff" placeholder="请扫描工单编号"
							border="none"></u--input>
						<uni-icons v-if="!$utils.isPda()" type="scan" size="22" color="#51d0d0"
							@click="rowOpenScan"></uni-icons>
					</u-form-item>
					<u-form-item prop="FWorkshopName" borderBottom>
						<view class="item-label">
							<uni-icons fontFamily="CustomFontPlatform"
								color="#808080">{{$utils.toUniCode('&#xe72a;')}}</uni-icons>
							<text class="label-text">生产车间</text>
							<text class="required">*</text>
						</view>
						<u--input :value="formData.FWorkshopName" disabled disabledColor="#fff" placeholder="由工单带出"
							border="none"></u--input>
					</u-form-item>
					<u-form-item prop="Comment" borderBottom>
						<view class="item-label">
							<uni-icons fontFamily="CustomFontPlatform"
								color="#808080">{{$utils.toUniCode('&#xec07;')}}</uni-icons>
							<text class="label-text">备注</text>
						</view>
						<u--input v-model="formData.Comment" placeholder="请输入" border="none"></u--input>
					</u-form-item>
				</u--form>
			</view>
		</view>

		<!-- 子表信息 -->
		<view class="detail">
			<!-- 子表页签 -->
			<view class="detail-label">
				<view :class="tabIndex==1?'on':''" @click="tabIndex = 1;">入库明细</view>
				<view :class="tabIndex==2?'on':''" @click="tabIndex = 2;">工单明细</view>
			</view>

			<!-- 入库明细 -->
			<view v-show="tabIndex==1">
				<u-empty v-show="!formDetail.length" icon="/static/image/Img/DataEmpty.png" :style="{height:srvHeight}"
					text="暂无入库明细"></u-empty>
				<scroll-view v-show="formDetail.length" class="rowContainer" :style="{height:srvHeight}"
					:scroll-y="true" :scroll-with-animation="true" :scroll-into-view="'section'+scanRow">
					<view :id="'section'+index" class="productRow" :class="scanRow==index ? 'b-p' : 'b-p-t'"
						v-for="(row,index) in formDetail" @click="setScanRow(index)">
						<view class="productRow-title">
							<view style="flex: 1;">【{{index+1}}】{{row.ProductName}}
								<text style="margin-left: 5px;color: #0000FF;">库存单位：{{row.UnitName}}</text>
							</view>
						</view>
						<view class="productRow-main">
							<view class="total-wrap">
								<text class="total-label">
									账面库存:
								</text>
								<text class="total-value">
									{{row.InventoryQty}}
								</text>
							</view>
							<view class="total-wrap">
								<text class="total-label">
									可入数量:
								</text>
								<text class="total-value">
									{{row.SYQty}}
								</text>
							</view>
						</view>
						<view class="productRow-main">
							<view class="total-wrap">
								<text class="total-label">
									剩余未入:
								</text>
								<text class="total-value">
									{{get_LL_SYQty(row)}}
								</text>
							</view>
							<view class="total-wrap">
								<text class="total-label">
									扫码合计:
								</text>
								<text class="total-value">
									{{row.scannedQty}}
								</text>
							</view>
						</view>
						<view class="productRow-main">
							<text v-if="!formData.Approve" class="del-title">删除</text>
							<text class="batch-title">仓库</text>
							<text class="pos-title">库位</text>
							<text class="qty-title">数量</text>
						</view>

						<view v-for="(item,itemIndex) in row.batchCodeArray" class="productRow-subWrap">
							<view class="productRow-sub">
								<view v-if="!formData.Approve" @click.stop="deleteCode(row, item, index, itemIndex)"
									class="del-content">
									<uni-icons fontFamily="CustomFontPlatform" :size="16"
										color="#c0392b">{{$utils.toUniCode('&#xeaaa;')}}</uni-icons>
								</view>
								<view class="batch-title">{{item.FWarehouseName}}</view>
								<view class="pos-content" @click.stop="changePosition(index,itemIndex)">
									<text :class="[!formData.Approve ? 'isEdit' : '']">{{item.posname}}</text>
								</view>
								<view class="qty-content" @click.stop="showChange(row,index,item,itemIndex)">
									<text :class="[!formData.Approve ? 'isEdit' : '']">{{item.qty}}</text>
								</view>
							</view>
							<view class="productRow-main">
								<view class="total-wrap">
									<text class="total-label">
										批次:
									</text>
									<text class="total-value">
										{{item.batch}}
									</text>
								</view>
							</view>
						</view>
					</view>
				</scroll-view>
			</view>

			<!-- 工单明细 -->
			<view v-show="tabIndex==2">
				<view>
					<u-empty v-show="!sourceDetail.length" icon="/static/image/Img/DataEmpty.png"
						:style="{height:srvHeight}" text="暂无工单明细"></u-empty>
					<m-table v-show="sourceDetail.length" ref="table" :height="srvHeight" :headers="headers"
						:contents="sourceDetail" :font-size="[$utils.px2rpx(12)]" :first-line-fixed="true"
						first-col-bg-color="#fff"></m-table>
				</view>
			</view>

		</view>

		<!-- 底部按钮 -->
		<view class="bottom" :style="$utils.disposeSafeBottomFun()">
			<u-button v-if="!formData.Approve" size="small" color="#51d0d0" :disabled="ifConfirm" :loading="ifConfirm"
				@click="confirmSubmit">保存单据</u-button>
			<u-button v-if="!formData.Approve && formData.FStockID" size="small" color="#c0392b" :disabled="ifConfirm"
				:loading="ifConfirm" @click="confirmApprove">审核</u-button>
			<u-button v-if="formData.Approve" size="small" color="#c0392b" :disabled="ifConfirm" :loading="ifConfirm"
				@click="approveFunction">取消审核</u-button>
		</view>

		<!-- 子表数值修改弹窗 -->
		<u-modal :show="showChangePanel" :showCancelButton="true" :closeOnClickOverlay="true" confirmColor="#51d0d0"
			:duration="0" title="数量修改" @confirm="confirmChange" @cancel="cancelChange" @close="closeChange">
			<!-- <u--input ref="input" type="digit" v-model="newValue" focus fontSize="20px" color="#666666" border="none"
				clearable placeholder="请输入修改数量"></u--input> -->
			<!-- 适配低性能设备输入框 -->
			<input ref="input" type="digit" v-model="newValue" focus fontSize="20px" color="#666666" border="none"
				clearable placeholder="请输入修改数量"></input>
		</u-modal>

		<!-- 控制弹窗显示 -->
		<uni-popup ref="popupRef" type="bottom" :is-mask-click="false">
			<view class="popup-container">
				<view class="popup-title">选择仓库库位</view>
				<view class="record-row" style="padding: 3px 8px;">
					<view class="record-item">
						<text class="record-item-label">物料编码：</text>
						<text class="record-item-value">{{ posInvList.length ? posInvList[0].ProductCode : '' }}</text>
					</view>
					<view class="record-item">
						<text class="record-item-label">物料批号：</text>
						<text class="record-item-value">{{ posInvList.length ? posInvList[0].FBatchNo : '' }}</text>
					</view>
				</view>
				<view class="record-row" style="padding: 3px 8px;">
					<view class="record-item">
						<text class="record-item-label">可入数量：</text>
						<text class="record-item-value">{{ SYQty }}</text>
					</view>
					<view class="record-item">
						<text class="record-item-label" style="color: #c0392b !important;">本次选择：</text>
						<text class="record-item-value" style="color: #c0392b !important;">{{ get_Select_Qty()}}</text>
					</view>
				</view>
				<view class="record-row" style="padding: 3px 8px;">
					<view class="record-item">
						<text class="record-item-label">剩余可入：</text>
						<text class="record-item-value">{{ LL_SYQty }}</text>
					</view>
					<view class="record-item">
						<text class="record-item-label">扫码合计：</text>
						<text class="record-item-value">{{ scannedQty}}</text>
					</view>
				</view>
				<uni-segmented-control :current="PopupTabIndex" :values="PopupItems" style-type="button"
					active-color="#51d0d0" @clickItem="onClickPopupItem" />
				<u-empty v-if="!getCurPosInvList(PopupTabIndex).length" icon="/static/image/Img/DataEmpty.png"
					:style="{height:'auto'}" text="暂无明细"></u-empty>

				<scroll-view v-if="getCurPosInvList(PopupTabIndex).length" scroll-y class="popup-scroll">
					<view v-for="(item, index) in getCurPosInvList(PopupTabIndex)" :key="index"
						:class="['record-block',item.inputQty>0 ? 'record-block-changed' : '']">

						<view class="record-row" v-if="PopupTabIndex == 1">
							<view class="record-item">
								<text class="record-item-label">物料编码：</text>
								<text class="record-item-value">{{ item.ProductCode }}</text>
							</view>
							<view class="record-item">
								<text class="record-item-label">库存批次：</text>
								<text class="record-item-value">{{ item.InventoryFBatchNo }}</text>
							</view>
						</view>

						<view class="record-row" v-if="PopupTabIndex == 0">
							<view class="record-item">
								<text class="record-item-label">默认仓库：</text>
								<text class="record-item-value">{{ item.DefaultFWarehouseName }}</text>
							</view>
							<view class="record-item">
								<text class="record-item-label">默认库位：</text>
								<text class="record-item-value">{{ item.DefaultFStorageCode }}</text>
							</view>
						</view>

						<view class="record-row">
							<view class="record-item" @click.stop="changeInvPosition(index,'弹窗入库仓库')">
								<text class="record-item-label">入库仓库：</text>
								<text v-if="item.FWarehouseName" class="record-item-value"
									:class="[PopupTabIndex == 0 ? 'isEdit' : '']">{{ item.FWarehouseName }}</text>
								<text v-if="!item.FWarehouseName && PopupTabIndex==0" class="record-item-value"
									style="color: #0000FF;">请选择</text>
							</view>
							<view class="record-item" @click.stop="changeInvPosition(index,'弹窗入库库位')">
								<text class="record-item-label">入库库位：</text>
								<text v-if="item.FStorageCode" class="record-item-value"
									:class="[PopupTabIndex == 0 ? 'isEdit' : '']">{{ item.FStorageCode }}</text>
								<text v-if="!item.FStorageCode && PopupTabIndex==0 " class="record-item-value"
									style="color: #0000FF;">请选择</text>
							</view>
						</view>

						<view class="record-row">
							<view class="record-item" v-if="PopupTabIndex==1">
								<text class="record-item-label">库存数量：</text>
								<text class="record-item-value">{{ item.InventoryQty }}</text>
							</view>
							<view class="record-item">
								<text class="record-item-label">库存单位：</text>
								<text class="record-item-value">{{ item.UnitName }}</text>
							</view>
						</view>

						<view class="record-row">
							<view class="record-item">
								<text class="record-item-label">入库数量：</text>

								<input style="color: #0000FF;" v-model="item.inputQty" type="digit" placeholder="请输入"
									:custom-style="{
																			border: 'none',
																			borderBottom: '1px solid #ccc',
																			padding: '0'
																		  }" input-align="left" @blur="() => validateItem(item)">

								<u-button @click="put_Qty(item)" text="默认带入" type="primary" size="mini"></u-button>

								</u-input>
							</view>
						</view>
					</view>
				</scroll-view>

				<view class="popup-footer">
					<button class="btn btn-default" @click="cancelInvSel">关闭</button>
					<button class="btn btn-primary" @click="confirmInvSel">确认</button>
				</view>
			</view>
		</uni-popup>

		<!-- PDA扫码 -->
		<m-pda-scancode v-if="$utils.isPda()" listenName="BatchEditScan"
			:SetContent="{action:$store.state.systemConfig.sysDeviceInfo.broadcastAction,extra:$store.state.systemConfig.sysDeviceInfo.broadcastResult}"></m-pda-scancode>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				titleName: '',
				currenTabIndex: 0, // 表头tab当前index
				items: ['基本项'], //	表头tab名称

				posInvList: [],
				posInvIndex: 0,
				PopupTabIndex: 0,
				PopupItems: ['库位选择', '批次库位库存'],
				posInvList_1: [],
				posInvList_2: [],

				scanDisabled: false,
				ifConfirm: false,
				showChangePanel: false,
				scanRow: 0, // 当前扫码行
				headTabWrapHeight: 0, //	表头tab容器高度
				headTabContentHeight: 0, //	表头tab内容高度
				detailLabelHeight: 0, // 切换标签高度
				bottomHeight: 0, // 底部按钮高度
				srvHeight: 'auto', // scrollview高度
				oldValue: '',
				newValue: '',
				posRow: 0,
				posIdx: 0,
				formData: {
					FStockID: 0,
					FCode: '',
					FDate: '',
					FWarehouseID: 0,
					FWarehouseName: '',
					FWorkshopID: 0,
					FWorkshopName: '',
					FStorageID: 0,
					FStorageCode: '',
					BillNO: '',
					Comment: '',
					Approve: 0
				},
				tabIndex: 1, // 子表页签
				formDetail: [],
				sourceDetail: [],
				headers: [{
						label: '序号',
						key: 'seq',
						width: 100
					},
					{
						label: '物料名称',
						key: 'ProductName',
						width: 360
					},
					{
						label: '单位',
						key: 'UnitName',
						width: 180
					},
					{
						label: '计划数量',
						key: 'FPlanQty',
						width: 180
					},
					{
						label: '已入库数量',
						key: 'WCQty',
						width: 180
					},
					{
						label: '剩余未入数量',
						key: 'SYQty',
						width: 180
					}
				],

				scannedQty: 0,
				SYQty: 0,
				LL_SYQty: 0,
			}
		},

		created() {

		},

		mounted() {
			let that = this;

			// 监听下拉回调
			uni.$on('BatchEditChoice', function(ret) {
				let selectItem = ret.data;


				if (ret.type == '子表库位') {
					let matchItem = that.formDetail[that.posRow].batchCodeArray[that.posIdx];
					matchItem.posid = selectItem.FStorageID;
					matchItem.posname = selectItem.FStorageCode;
				}

				if (ret.type == '弹窗入库仓库') {
					let matchItem = that.getCurPosInvList(that.PopupTabIndex)[that.posInvIndex];
					if (selectItem.FWarehouseID != matchItem.FWarehouseID) {
						matchItem.FWarehouseID = selectItem.FWarehouseID;
						matchItem.FWarehouseName = selectItem.FWarehouseName;
						matchItem.FStorageID = 0;
						matchItem.FStorageCode = '';
					}

				}

				if (ret.type == '弹窗入库库位') {
					let matchItem = that.getCurPosInvList(that.PopupTabIndex)[that.posInvIndex];
					matchItem.FStorageID = selectItem.FStorageID;
					matchItem.FStorageCode = selectItem.FStorageCode;
					that.changePopupItemsValue(that.PopupTabIndex, that.checkTabHasValue(that.PopupTabIndex))

				}
			})

			// PDA扫码处理
			uni.$on('BatchEditScan', function(content) {
				let scanData = that.$utils.wmsFun.scanTransf(content);
				that.scanHandler(scanData);
			})

			// 动态计算元素高度
			that.getElementHeights();
		},

		methods: {

			// 显示隐藏面板
			togglePanel() {
				if (this.currenTabIndex == null) {
					this.currenTabIndex = 0;
				} else {
					this.currenTabIndex = null;
				}
				this.changeTabContentHeight();
			},

			// 切换表单面板
			onClickItem(e) {
				if (this.currenTabIndex != e.currentIndex) {
					this.currenTabIndex = e.currentIndex;
					this.changeTabContentHeight();
				}
			},
			onClickPopupItem(e) {
				if (this.PopupTabIndex != e.currentIndex) {
					this.PopupTabIndex = e.currentIndex;
				}
			},
			changeTabContentHeight() {
				const query = uni.createSelectorQuery().in(this);
				this.$nextTick(() => {
					query.select('.headTabContent').boundingClientRect(rect => {
						this.headTabContentHeight = rect.height;
						console.log(this.headTabContentHeight);
						this.calcSrvHeight(this.headTabContentHeight);

					}).exec();
				})
			},

			// 获取单据详情
			getPageData() {
				let that = this;
				that.Request.request('batchCode_cprkDtl', {
						FStockID: that.formData.FStockID
					}, function(res) {
						let data = res.data;

						// 1.初始化表头信息
						that.formData.FDate = data.ds[0].FDate;
						that.formData.FCode = data.ds[0].FCode;
						that.formData.FWorkshopID = data.ds[0].FWorkshopID;
						that.formData.FWorkshopName = data.ds[0].FWorkshopName;
						that.formData.BillNO = data.ds[0].BillNO;
						that.formData.Comment = data.ds[0].Comment;
						that.formData.Approve = data.ds[0].Approve;

						// 2.初始化批次码入库明细
						var formDetail = [];
						for (var i in data.ds1) {
							var x = 0;
							for (var j in formDetail) {
								if (formDetail[j].ProductID == data.ds1[i].ProductID && formDetail[j]
									.WoOrderID == data.ds1[i].WoOrderID) {
									x = 1;
									formDetail[j].batchCodeArray.push({
										FStockDeID: data.ds1[i].FStockDeID,
										batch: data.ds1[i].FBatchNo,
										qty: data.ds1[i].FQty,
										FWarehouseID: data.ds1[i].FWarehouseID,
										FWarehouseName: data.ds1[i].FWarehouseName,
										posid: data.ds1[i].FStorageID,
										posname: data.ds1[i].FStorageCode
									})
								}
							}

							if (x == 0) {
								if (data.ds1[i].FQty == 0) {
									formDetail.push({
										ProductID: data.ds1[i].ProductID,
										ProductCode: data.ds1[i].ProductCode,
										ProductName: data.ds1[i].ProductName,
										WoOrderID: data.ds1[i].WoOrderID,
										WSQty: data.ds1[i].WSQty,
										WCQty: data.ds1[i].WCQty,
										SYQty: data.ds1[i].SYQty,
										InventoryQty: data.ds1[i].InventoryQty,
										UnitName: data.ds1[i].UnitName,
										scannedQty: 0,
										batchCodeArray: []
									})
								} else {
									formDetail.push({
										ProductID: data.ds1[i].ProductID,
										ProductCode: data.ds1[i].ProductCode,
										ProductName: data.ds1[i].ProductName,
										WoOrderID: data.ds1[i].WoOrderID,
										WSQty: data.ds1[i].WSQty,
										WCQty: data.ds1[i].WCQty,
										SYQty: data.ds1[i].SYQty,
										InventoryQty: data.ds1[i].InventoryQty,
										UnitName: data.ds1[i].UnitName,
										scannedQty: 0,
										batchCodeArray: [{
											FStockDeID: data.ds1[i].FStockDeID,
											batch: data.ds1[i].FBatchNo,
											qty: data.ds1[i].FQty,
											FWarehouseID: data.ds1[i].FWarehouseID,
											FWarehouseName: data.ds1[i].FWarehouseName,
											posid: data.ds1[i].FStorageID,
											posname: data.ds1[i].FStorageCode
										}]
									})
								}
							}
						}
						formDetail.forEach((row, index) => that.calcRowTotal(row, index));
						that.formDetail = formDetail;

						that.sourceDetail = data.ds2.map((item, index) => ({
							...item,
							seq: index + 1
						}));
					},
					function(err) {}, that.Request.IPAgreement() + that.Request.serverIP() +
					'/Frame/SqlData', 1)
			},

			// 保存单据
			confirmSubmit(index) {
				let that = this;

				let isEmpty = that.formDetail.every(item => item.scannedQty == 0);
				if (isEmpty) {
					that.$utils.msg('入库明细不能为空!');
					return false;
				} else {
					let FWoOrderIDs = [],
						FProductCodes = [],
						FWarehouseIDs = [],
						FStorageIDs = [],
						FBatchNos = [],
						FQtys = []

					for (let i = 0; i < that.formDetail.length; i++) {
						let row = that.formDetail[i];

						for (let j = 0; j < row.batchCodeArray.length; j++) {
							let batchCode = row.batchCodeArray[j];

							FWoOrderIDs.push(row.WoOrderID);
							FProductCodes.push(row.ProductCode);
							FWarehouseIDs.push(batchCode.FWarehouseID);
							FStorageIDs.push(batchCode.posid);
							FBatchNos.push(batchCode.batch);
							FQtys.push(batchCode.qty);
						}
					}
					let obj = {
						FStockID: that.formData.FStockID,
						FWorkshopID: that.formData.FWorkshopID,
						Comment: that.formData.Comment,
						FWoOrderIDs: FWoOrderIDs.join(','),
						FProductCodes: FProductCodes.join(','),
						FWarehouseIDs: FWarehouseIDs.join(','),
						FStorageIDs: FStorageIDs.join(','),
						FBatchNos: FBatchNos.join(','),
						FQtys: FQtys.join(',')
					}

					if (index == 1) {
						that.saveFunction(obj, index);
					} else {
						uni.showModal({
							title: '提示',
							content: '是否保存当前单据',
							success: function(res) {
								if (res.confirm) {
									that.saveFunction(obj, index);
								} else if (res.cancel) {
									// console.log('用户点击取消');
								}
							}
						})
					}

				}

			},

			// 保存单据
			saveFunction(obj, index) {
				let that = this;

				that.Request.request(that.formData.FStockID == 0 ? 'batchCode_cprkAdd' :
					'batchCode_cprkEdit', obj,
					function(res) {
						let data = res.data;

						if (data.ds[0].status == 500) {
							uni.showModal({
								title: '提示',
								content: data.ds[0].msg,
								showCancel: false,
								confirmText: '确定',
								success: (res) => {
									if (res.confirm) {
										// console.log('用户点击确定');
									} else if (res.cancel) {
										// console.log('用户点击取消');
									}
								},
							});
						} else {
							if (that.formData.FStockID == 0) {
								that.formData.FStockID = data.ds[0].FStockID;
								if (index != 1) {
									that.$utils.msg('保存成功!');
								}
							} else {
								if (index != 1) {
									that.$utils.msg('修改成功!');
								}
							}
							that.getPageData();
							if (index == 1) {
								that.approveFunction();
							}
							uni.$emit('BatchListRefresh')
						}
					},
					function(err) {}, that.Request.IPAgreement() + that.Request.serverIP() +
					'/Frame/SqlData', 1)
			},

			// 单据审核
			confirmApprove() {
				let that = this;
				that.confirmSubmit(1);
			},

			// 审核单据
			approveFunction() {
				let that = this;
				let obj = {
					FStockID: that.formData.FStockID,
					isApprove: that.formData.Approve
				};

				let contentStr = '';
				if (that.formData.Approve == 0) {
					contentStr = '是否提交审核?';
				} else if (that.formData.Approve == 1) {
					contentStr = '是否取消审核?'
				}

				uni.showModal({
					title: '提示',
					content: contentStr,
					success: function(res) {
						if (res.confirm) {
							that.Request.request('batchCode_cprkApprove', obj,
								function(res) {
									let data = res.data;
									if (data.ds[0].status == 500) {
										uni.showModal({
											title: '提示',
											content: data.ds[0].msg,
											showCancel: false,
											confirmText: '确定',
											success: (res) => {
												if (res.confirm) {
													// console.log('用户点击确定');
												} else if (res.cancel) {
													// console.log('用户点击取消');
												}
											},
										});
									} else {
										if (that.formData.Approve == 0) {
											that.$utils.msg('审核成功!');
										} else {
											that.$utils.msg('取消审核成功!');
										}
										that.getPageData();
										uni.$emit('BatchListRefresh')
									}
								},
								function(err) {}, that.Request.IPAgreement() + that.Request
								.serverIP() +
								'/Frame/SqlData', 1)
						} else if (res.cancel) {
							// console.log('用户点击取消');
						}
					}
				});
			},


			// 设置扫码物料行
			setScanRow(index) {
				this.scanRow = index;
			},

			// 删除物料批次条码
			deleteCode(row, item, index, itemIndex) {
				let that = this;
				uni.showModal({
					title: '提示',
					content: '确认删除仓库: ' + item.FWarehouseName + ' 库位: ' + item.posname + ' 批次: ' + item.batch +
						'的记录?',
					success: function(res) {
						if (res.confirm) {
							row.batchCodeArray.splice(itemIndex, 1);
							that.calcRowTotal(row, index);
							that.$utils.msg('批次条码删除成功!');
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				});
			},

			showChange(row, index, item, itemIndex) {
				if (!this.formData.Approve) {
					this.showChangePanel = true;
					this.oldValue = item.qty;
					this.newValue = item.qty;
					this.posRow = index;
					this.posIdx = itemIndex;
				}
			},

			confirmChange() {
				var value = this.newValue;

				if (!value) {
					this.$utils.msg('数量不能为零或空!');
				} else {
					let row = this.formDetail[this.posRow];
					let item = row.batchCodeArray[this.posIdx];

					let total = row.scannedQty - this.oldValue + Number(value);
					if (total > row.SYQty) {
						let remainedQty = Number(row.SYQty) - Number(row.scannedQty); // 本次超扫数量
						this.$utils.msg('剩余可入数量: ' + remainedQty + row.UnitName + '!');
					} else {
						if (Number(value) != this.oldValue) {
							this.$utils.msg('数量修改成功!');
						}
						item.qty = Number(value);
						this.calcRowTotal(row, this.posRow);
					}
				}

				this.showChangePanel = false;
			},

			cancelChange() {
				this.showChangePanel = false;
			},

			closeChange() {
				this.showChangePanel = false;
			},
			changeInvPosition(index, name) {
				let that = this;
				if (that.PopupTabIndex != 0) {
					return;
				}
				console.log(index);
				this.posInvIndex = index;
				this.openBaseScreen(name);
			},
			// 更改入库明细库位
			changePosition(index, itemIndex) {
				this.posRow = index;
				this.posIdx = itemIndex;
				this.openBaseScreen('子表库位');
			},

			// 计算合计扫码数量
			calcRowTotal(row, index) {
				const totalValue = row.batchCodeArray.reduce((acc, item) => acc + Number(item.qty), 0);
				row.scannedQty = totalValue;
			},

			// 打开摄像头
			openScan() {
				let that = this;
				this.$scanPopup.openScan({
					onlyFromCamera: true,
					scanType: ['qrCode'],
					success: (res) => {
						let scanData = that.$utils.wmsFun.scanTransf(res.result);
						that.scanHandler(scanData);
					}
				})
			},

			rowOpenScan() {
				this.openScan();
			},
			getSameInfo() { //获取相同物料明细行
				let that = this;
				let arr = that.formDetail;
				let SameArr = [];
				const count = {};

				// 统计每个 ProductCode 值出现的次数
				arr.forEach(obj => {
					const key = obj.ProductCode;
					count[key] = (count[key] || 0) + 1;
				});

				// 筛选出所有 ProductCode 值重复的对象
				arr.forEach(obj => {
					if (count[obj.ProductCode] > 1) {
						SameArr.push({
							ProductCode: obj.ProductCode
						});
					}
				});

				return SameArr;
			},
			IsCurRowBySameInfo(code) { //是否选中明细行中相同的物料之一
				console.log(code)
				let that = this;
				let arr = that.getSameInfo() || [];
				console.log(arr);
				let isExists = false;
				try {
					isExists = arr.some((item) => {
						return item.ProductCode == code
					})
				} catch (e) {
					isExists = false;

				}
				if (isExists) {
					return {
						isSame: true,
						isCurRow: (that.formDetail[that.scanRow].ProductCode == code) || false,
					}
				} else {
					return {
						isSame: false
					}
				}

			},
			// 扫码处理
			scanHandler(scanData) {
				let that = this;

				if (that.scanDisabled) {
					that.$utils.msg('数据提交中,请稍后再试!');
					return false;
				}
				if (!scanData) {
					that.$utils.msg('请扫描正确的条码!');
					return false;
				}
				if (that.formData.Approve) {
					that.$utils.msg('当前单据已审核!');
					return false;
				}

				if (scanData.type == '工单') {

					let obj = {
						WoOrderID: scanData.data.code
					}
					that.scanDisabled = true;
					that.Request.request('batchCode_cprkSource', obj, function(res) {
							that.scanDisabled = false;
							let data = res.data;

							if (data.ds[0].status == 500) {
								that.$utils.msg(data.ds[0].msg)
							} else {
								// 初始化主表信息
								that.formData.BillNO = data.ds[0].BillNO;
								that.formData.FWorkshopID = data.ds[0].FWorkshopID;
								that.formData.FWorkshopName = data.ds[0].FWorkshopName;

								that.sourceDetail = data.ds.map((item, index) => ({
									...item,
									seq: index + 1
								}));

								that.formDetail = data.ds.map((item, index) => ({
									...item,
									scannedQty: 0,
									batchCodeArray: []
								}));

								// 切换至工单明细tab
								that.tabIndex = 2;

							}
						}, function(err) {
							that.scanDisabled = false;
						}, that.Request.IPAgreement() + that.Request.serverIP() +
						'/Frame/SqlData', 1)

				} else if (scanData.type == '产品批次码') {

					if (!that.formData.BillNO) {

						that.$utils.msg('请扫描工单!')
						return false;
					}


					that.tabIndex = 1;

					let flag = that.formDetail.some(item => item.ProductCode == scanData.data.code);
					if (!flag) {
						that.$utils.msg('入库明细不存在当前物料!')
						return false;
					}

					let SameInfo = that.IsCurRowBySameInfo(scanData.data.code);
					console.log(SameInfo)
					if (SameInfo.isSame) {
						if (!SameInfo.isCurRow) {
							that.$utils.msg('当前扫描物料在明细中存在多条，请先选中一条!');
							return false;
						}

						let source = that.formDetail.filter(item => item.ProductCode == scanData.data.code) || [];
						let SYQty = source.reduce((acc, item) => (acc + Number(item.SYQty)), 0);
						let scannedQty = source.reduce((acc, item) => (acc + Number(item.scannedQty)), 0);
						if (Number(SYQty) - Number(scannedQty) <= 0) {
							that.$utils.msg('当前物料不存在可入库的明细!');
							return false;
						}

						let source_scanRow = that.formDetail[that.scanRow]
						if (Number(source_scanRow.SYQty) - Number(source_scanRow.scannedQty) <= 0) {
							uni.showModal({
								title: '提示',
								content: '当前物料行不存在可入库数量，是否自动选中下个该物料行？',
								success: function(res) {
									if (res.confirm) {
										let matchIndex = that.formDetail.findIndex((ele) => {
											return ele.ProductCode == scanData.data.code && Number(ele
												.SYQty) - Number(ele.scannedQty) > 0
										});
										that.setScanRow(matchIndex)

									} else if (res.cancel) {
										// console.log('用户点击取消');								
									}
								}
							})
							return false;
						}
					} else {
						let matchIndex = that.formDetail.findIndex((ele) => {
							return ele.ProductCode == scanData.data.code
						});
						that.setScanRow(matchIndex)

						let source = that.formDetail[that.scanRow]
						if (Number(source.SYQty) - Number(source.scannedQty) <= 0) {
							that.$utils.msg('当前物料不存在可入库的明细!');
							return false;
						}
					}

					// let source = that.formDetail[that.scanRow]
					// if (Number(source.SYQty) - Number(source.scannedQty) <= 0) {
					// 	that.$utils.msg('当前物料不存在可入库的明细!');
					// 	return false;
					// }

					that.SYQty = that.formDetail[that.scanRow].SYQty || 0;
					that.scannedQty = that.formDetail[that.scanRow].scannedQty || 0;
					that.LL_SYQty = that.get_LL_SYQty(that.formDetail[that.scanRow]) || 0;


					that.scanDisabled = true;
					that.PopupTabIndex = 0;

					that.Request.request('batchCode_getDefault', {
							ProductCode: scanData.data.code,
							FBatchNo: scanData.data.batch
						}, function(res) {

							that.scanDisabled = false;

							let data = res.data;
							if (data.ds[0].status == 500) {
								that.$utils.msg(data.ds[0].msg);
							} else {
								let sourceData = that.formDetail[that.scanRow]

								that.posInvList = data.ds.map(item => {
									return {
										...item,

										WoOrderID: sourceData.WoOrderID,
										scannedQty: sourceData.scannedQty,
										SYQty: sourceData.SYQty,

										DefaultFWarehouseID: item.FWarehouseID,
										DefaultFWarehouseName: item.FWarehouseName,
										DefaultFStorageID: item.FStorageID,
										DefaultFStorageCode: item.FStorageCode,
										FWarehouseID: item.FWarehouseID,
										FWarehouseName: item.FWarehouseName,
										FStorageID: item.FStorageID,
										FStorageCode: item.FStorageCode,
										ProductCode: item.ProductCode,
										FBatchNo: item.FBatchNo,
										inputQty: '',

									}
								});
								if (that.posInvList.length) {
									that.posInvList_1 = that.posInvList.filter((item) => {
										return item.type == 1
									}) || [];

									that.posInvList_2 = that.posInvList.filter((item) => {
										return item.type == 2
									}) || [];

									console.log(that.posInvList_1)
									console.log(that.posInvList_2)
									that.PopupItems.forEach((item, index) => {
										that.changePopupItemsValue(index);
									})
									that.$refs.popupRef.open();
								} else {
									that.$utils.msg('请重试!');
									return false;
								}
							}
						}, function(err) {
							that.scanDisabled = false;
						}, that.Request.IPAgreement() + that.Request.serverIP() +
						'/Frame/SqlData', 1)

				} else {
					that.$utils.msg('请扫描工单二维码或产品批次码！！');
				}
			},
			getCurPosInvList(type) {
				let that = this;
				console.log(type)
				console.log(that[`posInvList_${type+1}`])
				return that[`posInvList_${type+1}`];
			},
			// 获取相关元素高度
			getElementHeights() {
				this.$nextTick(() => {
					const query = uni.createSelectorQuery().in(this);
					const promises = [];
					// 获取每个元素的高度，并返回一个 Promise
					const getHeightPromise = (selector) => {
						return new Promise((resolve) => {
							query.select(selector).boundingClientRect((rect) => {
								resolve(rect.height);
							}).exec();
						});
					};

					promises.push(getHeightPromise('.headTabWrap'));
					promises.push(getHeightPromise('.headTabContent'));
					promises.push(getHeightPromise('.detail-label'));
					promises.push(getHeightPromise('.bottom'));

					// 等待所有 Promise 完成
					Promise.all(promises).then((heights) => {
						console.log(heights);
						this.headTabWrapHeight = heights[0];
						this.headTabContentHeight = heights[1];
						this.detailLabelHeight = heights[2];
						this.bottomHeight = heights[3];

						this.calcSrvHeight(this.headTabContentHeight);
					});
				})
			},

			// 重新计算scrollview高度
			calcSrvHeight(headTabContentHeight) {
				let safeAreaTop = this.$u.sys().statusBarHeight;
				let height =
					`calc(100vh - 44px - ${safeAreaTop}px - ${this.headTabWrapHeight}px - ${headTabContentHeight}px - ${this.detailLabelHeight}px - ${this.bottomHeight}px)`;
				this.srvHeight = height;
				console.log(this.srvHeight);
			},

			// 公共下拉选择
			openBaseScreen(str) {
				let url = '/commonPage/Tool/baseScreen';
				let obj;

				if (str == '子表库位') {
					obj = {
						allowClear: false,
						cmd: 'Droplist_Storage',
						type: str,
						ListeningName: 'BatchEditChoice',
						refresherEnabled: false,
						serverSearch: {
							isPaging: false, //是否分页
							searchKey: 'FStorageCode',
							showText: 'FStorageCode', //查询结果显示的字段
							ChoiceDataKey: 'FStorageID',
							ChoiceDataData: this.formDetail[this.posRow].batchCodeArray[this.posIdx].posid
						},
						param: {
							FWarehouseID: this.formDetail[this.posRow].batchCodeArray[this.posIdx].FWarehouseID
						}
					}
				}

				if (str == '弹窗入库仓库') {
					let match_posInvList = this.getCurPosInvList(this.PopupTabIndex)[this.posInvIndex]
					obj = {
						allowClear: false,
						cmd: 'Droplist_Warehouse',
						type: str,
						ListeningName: 'BatchEditChoice',
						refresherEnabled: false,
						serverSearch: {
							isPaging: false, //是否分页
							showText: 'FWarehouseName', //查询结果显示的字段
							ChoiceDataKey: 'FWarehouseID',
							ChoiceDataData: match_posInvList.FWarehouseID
						},
						param: {

						}
					}
				}

				if (str == '弹窗入库库位') {
					let match_posInvList = this.getCurPosInvList(this.PopupTabIndex)[this.posInvIndex]
					if (!match_posInvList.FWarehouseID) {
						this.$utils.msg('请先选择入库仓库!');
						return false;
					}

					obj = {
						allowClear: false,
						cmd: 'Droplist_Storage',
						type: str,
						ListeningName: 'BatchEditChoice',
						refresherEnabled: false,
						serverSearch: {
							isPaging: false, //是否分页
							searchKey: 'FStorageCode',
							showText: 'FStorageCode', //查询结果显示的字段
							ChoiceDataKey: 'FStorageID',
							ChoiceDataData: match_posInvList.FStorageID
						},
						param: {
							FWarehouseID: match_posInvList.FWarehouseID,
						}
					}
				}


				this.$store.commit('ChangeAndSetStateData', {
					Name1: 'BaseScreenParm',
					data: obj
				})

				uni.navigateTo({
					url: url
				})
			},
			validateItem(item) {
				let that = this;
				const qty = parseFloat(item.inputQty);
				if (qty <= 0) {
					that.$utils.msg('入库数量必须大于0');
					item.inputQty = '';
					return false;
				}
				if (qty > (Number(item.SYQty) - Number(item.scannedQty) - that.get_Select_Qty() + qty)) {
					let remainedQty = Number(item.SYQty) - Number(item.scannedQty) - that.get_Select_Qty() + qty;
					that.$utils.msg('剩余可入数量: ' + remainedQty + item.UnitName + '!');
					item.inputQty = remainedQty;
					return false;
				}

				if (!item.FStorageCode && qty) {
					that.$utils.msg('存在已填写数量但未选择入库库位的明细！！');
					return false;
				}

				that.changePopupItemsValue(that.PopupTabIndex, that.checkTabHasValue(that.PopupTabIndex))

				return true;
			},
			confirmInvSel() {
				let that = this;
				let selectedItem = this.posInvList.filter((item) => {
					return item.inputQty > 0 && item.FStorageCode
				})

				if (selectedItem.length) {

					let totalQty = selectedItem.reduce((acc, obj) => acc + +obj.inputQty, 0)
					console.log(totalQty)
					console.log(selectedItem[0].SYQty)
					console.log(selectedItem[0].scannedQty)

					if ((totalQty + selectedItem[0].scannedQty) > selectedItem[0].SYQty) {
						that.$utils.msg('总数超出剩余可入数量！！');
						return false;
					}

					let matchIndex = null;
					let matchRow = [];
					let batchCode = {};
					selectedItem.forEach((item) => {
						matchIndex = that.scanRow;
						matchRow = that.formDetail[matchIndex];

						batchCode = {
							...item,
							FStockDeID: 0,
							batch: item.FBatchNo,
							qty: Number(item.inputQty),
							FWarehouseID: item.FWarehouseID,
							FWarehouseName: item.FWarehouseName,
							posid: item.FStorageID,
							posname: item.FStorageCode,
						}

						matchRow.batchCodeArray.unshift(batchCode);

						that.setScanRow(matchIndex);

						that.calcRowTotal(matchRow, matchIndex);
					})

					that.$refs.popupRef.close();
				} else {
					that.$utils.msg('数量和库位不能为空！！');
				}

			},
			// 库位批次库存-取消
			cancelInvSel() {
				this.$refs.popupRef.close();
			},
			put_Qty(item) {
				let that = this;
				let qty = item.inputQty || 0;
				item.inputQty = (Number(item.SYQty) - Number(item.scannedQty) - that.get_Select_Qty() + qty)
				that.validateItem(item);
			},
			checkTabHasValue(index) {
				let that = this;
				let flag = false;
				try {
					flag = that.getCurPosInvList(index).some((item) => {
						return item.inputQty > 0 && item.FStorageCode
					});
				} catch (e) {
					console.log(e);
					flag = false;
				}
				console.log(flag)

				return flag
			},
			changePopupItemsValue(index, hasValue = false) {
				let arr = ['库位选择', '批次库位库存'];
				let str = '☑';
				let value = hasValue ? `${str}${arr[index]}` : arr[index];

				this.$set(this.PopupItems, index, value);
			},
			get_LL_SYQty(item) {
				let that = this;
				let LL_SYQty = 0
				try {
					LL_SYQty = !that.formData.Approve ? (Number(item.SYQty) - Number(item.scannedQty)) : Number(item.SYQty)
				} catch (e) {
					console.log(e)
					LL_SYQty = 0
				}
				return LL_SYQty
			},
			get_Select_Qty() {
				let that = this;
				console.log(that.posInvList)
				let selectedItem = that.posInvList.filter((item) => {
					return item.inputQty > 0 && item.FStorageCode
				})
				let totalQty = 0
				try {
					totalQty = selectedItem.reduce((acc, obj) => acc + +obj.inputQty, 0)
				} catch (e) {
					console.log(e)
					totalQty = 0
				}
				return totalQty

			},
		},

		onLoad(option) {
			let menuName = decodeURIComponent(option.menuName);
			this.titleName = menuName + '详情';
			this.formData.FStockID = parseInt(option.FStockID);

			if (this.formData.FStockID != 0) {
				this.getPageData();
			} else {
				this.formData.FDate = this.$utils.dateFormat(new Date(), 'Y-MM-dd');
			}
		},

		onUnload() {
			uni.$off('BatchEditChoice');
			uni.$off('BatchEditScan');
		}
	}
</script>

<style lang="scss" scoped>
	@import "@/static/assets/scss/wms.scss";
</style>